package com.forevershine.action;
import static com.forevershine.common.util.FileUtils.appendTimeStampToFileName;
import static com.forevershine.common.util.GsonConverter.fromObj;
import static com.forevershine.common.util.HttpRequestResponseHelper.writeJsonResponse;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {

	private static final long serialVersionUID = 3312677195014544590L;
	private static final String UPLOAD_PATH = "\\upload\\";
	private static SimpleDateFormat sdFormat = new SimpleDateFormat(
			"yyyyMMddHHmmss");
	private static final int BUFFER_SIZE = 4096;
	
	private static final String FILENAME_APPENDIX= "FileName";

	

	public void uploadFile() throws Exception {
		Map<String, Object> params =ActionContext.getContext().getParameters();
		File fileToUpload  =null;
		String fileName =null;
		String contentType =null;
		for(Map.Entry<String, Object> entry : params.entrySet())
		{
			if (entry.getValue() instanceof File[])
			{
				fileToUpload = ((File[])entry.getValue())[0];
			}
			else
			{
				String key = entry.getKey();
				if (key.substring(key.length()-FILENAME_APPENDIX.length()).equals(FILENAME_APPENDIX))
				{
					fileName =((String[])entry.getValue())[0].toString();
				}
				else
				{
					contentType = ((String[])entry.getValue())[0].toString();
				}
			}
		}
		
		String savePath = ServletActionContext.getServletContext().getRealPath("")+UPLOAD_PATH;
		String trueFileName = appendTimeStampToFileName(fileName);
		String filePath = savePath + trueFileName ;
		

		uploadImage(fileToUpload, filePath);

		
			HashMap responseMap = new HashMap();
			responseMap.put("filepath", "upload/"+trueFileName);
			if (contentType.contains("image"))
			{
				responseMap.put("image","true");
			}
			writeJsonResponse(fromObj(responseMap));		
	}

	// copy temporary file (generated by struts uploading components) and rename
	// it to the file specified by "filePath".
	private void uploadImage(File srcFile, String filePath) throws IOException {
		FileOutputStream fos = new FileOutputStream(new File(filePath));
		InputStream in = new BufferedInputStream(new FileInputStream(srcFile),
				BUFFER_SIZE);
		OutputStream out = new BufferedOutputStream(fos, BUFFER_SIZE);
		try {
			byte[] buffer = new byte[BUFFER_SIZE];
			while (in.read(buffer) > 0) {
				out.write(buffer);
			}
			fos.flush();
		} finally {
			
			in.close();
			out.close();
		}
	}


}
